<!DOCTYPE html>
<html manifest="demo.appcache">
       <head>
       <title>Register</title>
       <script type="text/javascript" src="scripts/jquery-1.11.0.min.js"></script>
       <script src="scripts/scripts.js" type="text/javascript"></script>
       <link rel="stylesheet" href="styles/styles.css" type="text/css" />
       <script type="text/javascript" src="scripts/jquery.js"></script>
       <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
       <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
       <script type="text/javascript">
 
         $(document).ready(function(){
            $("#username").change(function(){
                 $("#message").html("<img src='img/ajax_loader.gif' /> checking...");       
 
            var username=$("#username").val();
 
              $.ajax({
                    type:"post",
                    url:"check.php",
                    data:"username="+username,
                        success:function(data){
                        if(data==0){
                            $("#message").html("<img src='img/checkmark.png' class='feedbackIcon'/> Username available");
                        }
                        else{
                            $("#message").html("<img src='img/delete.png' class='feedbackIcon'/> Username already taken");
                        }
                    }
                 });
 
            });
 
         });
       </script>
       </head>
       <?php
require 'config.php' ;
require 'functions.php';
//////////////////////////////////////////////////// 	REGISTER NEW STUDENT

// define variables and set to empty values
$firstNameErr = $lastNameErr = $usernameErr = $emailErr = $passwordErr = $loginErr = "";
$firstName = $lastName = $username = $email = $password = "";
$attempt = 1;
$testID = 1;
//$_SESSION['attempt'] = $attempt ;

		
if ($_SERVER["REQUEST_METHOD"] == "POST")
{

//first name
	if (empty($_POST["firstName"]))
	{$firstNameErr = "First name is required";}
	else
	{
		$firstName = test_input($_POST["firstName"]);
		$_SESSION['firstName'] = $firstName;
		if (!preg_match("/^[a-zA-Z ]*$/",$firstName))
		{
			$firstNameErr = "Only letters please";
		}
	}
//last name
    if (empty($_POST["lastName"]))
    {
    $lastNameErr = "Last name is required";}
    else
    {
        $lastName = test_input($_POST["lastName"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$lastName))
        {
            $lastNameErr = "Only letters please";
        }
    }
//email	
    if (empty($_POST["email"]))
    {
    $emailErr = "Email is required"; }
    else
    {
        $email = ($_POST["email"]);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
            $emailErr = "Please enter a valid email address";
        }
	}
//password
	if (empty($_POST["password"]))
	{
	$passwordErr = "Password is required";}
	else
	{
	$password = test_input($_POST["password"]);
	}
		
// username	
	if (empty($_POST["username"]))
	{
	$usernameErr = "Username is required";
	}
	  else
	{
	$username = test_input($_POST["username"]);
	$_SESSION['username'] = $username;
	 if (!preg_match("/^[a-zA-Z0-9]*$/",$username))
		{
			$usernameErr = "Only numbers and letters please";
		}
		}
			
}		
function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}


if (empty($firstNameErr) && empty($lastNameErr) && empty($usernameErr) && empty($emailErr) && empty($passwordErr) && (isset($_POST['studentSubmit']))) {
$con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);   
	$query = "INSERT INTO student (firstName, lastName, username, email, password) VALUES ("
		. "'" . $firstName . "', "
		. "'" . $lastName . "', "
		. "'" . $username . "', "
		. "'" . $email . "', "
		. "'" . $password . "'"
		. ")"	;
$result = mysqli_query($con, $query);

header('LOCATION: controlpanel.php');
exit();
}
/////////////////////////////////////////////////////////////	LOG IN EXISTING STUDENT

if (isset($_POST['loginSubmit'])) {
 	$con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);   
	$query = "SELECT * FROM student WHERE username = "
	. "'" .  ($_POST["username"]) . "'" 
	.  " AND password =" 
	. "'" . ($_POST["password"]) . "'" 
	. "";
	$result = mysqli_query($con, $query);

$numberOfRows = mysqli_num_rows($result);
	if ($numberOfRows > 0) 
{	
while ($row = mysqli_fetch_array($result)) 
{
		extract($row); 
}
$getStudentByUN = getStudentByUN($_POST["username"]);
$getAttempts = getAttempts($studentID);

header('LOCATION: controlpanel.php');
exit();
}
else
{
 	$loginErr = "Invalid username or password.Please try again";
	$firstNameErr = $lastNameErr = $usernameErr = $emailErr = $passwordErr = "";
	$firstName = $lastName = $username = $email = $password = "";
}
}
?>
       <body>
<header>Learner Centred Design Formative Assessment</header>
<div id="container" class="one-edge-shadow">
         <div id="mainContent"> 
    <!--    <img src="img/Online-learning.jpg" height="120px" class="left"/>
-->
    <h1 id="pageTitle">Welcome to the Learner Centred Design Assessment</h1>
    <div>
             <p>In this assessment you will have the opportunity to demonstrate your understanding of what you have learned so far.</p>
             <p>Before you undertake the assessment please create an account. Once you have finished the assessment you will be able to view your results whenever you choose and compare them with earlier attempts. To get started, please register below:</p>
           </div>
    <div class="half left">
             <form id="newStudentForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="half">
      
       <fieldset>
                 <legend>First time here?</legend>                
                 <label for="firstName" class="formLabel">First Name*</label>
                 <span class="error"><?php echo $firstNameErr;?></span>
                 <input type="text" name="firstName" id="firstName" value="<?php echo $firstName;?>"/>
                 <label for="lastName" class="formLabel">Last Name*</label>
                 <span class="error"><?php echo $lastNameErr;?></span>
                 <input type="text" name="lastName" id="lastName" value="<?php echo $lastName;?>"/>
                 <label for="username" class="formLabel">Username*</label>
                 <span class="error"><?php echo $usernameErr;?></span><span id="message"></span>
                 <input type="text" name="username" id="username" value="<?php echo $username;?>" />
                 <label for="email" class="formLabel">Email*</label>
                 <span class="error"><?php echo $emailErr;?></span>
                 <input type="text" name="email" id="email" value="<?php echo $email;?>"/>
                 <label for="password" class="formLabel">Password*</label>
                 <span class="error"><?php echo $passwordErr;?></span>
                 <input type="password" name="password" id="password" value="<?php echo $password;?>" maxlength="8" />
                 <input type="hidden" name="attempt" value="<?php echo $attempt; ?>">
                 <input type="submit" id="studentSubmit" name="studentSubmit" value="Submit" class="btn" />
            	<p class="right">* Required field</p>     
            	</fieldset>
      </form>
           </div>
    <div class="half right">
             <form id="studentLogin" method="post" class="breathe half">
        <fieldset>
                 <legend>Returning user?</legend>
                 <input type="hidden" name="attempt" value="<?php echo $attempt ?>">
                 <label for="username" class="formLabel">Username</label>
                 <input type="text" name="username" id="usernameLogin" value="<?php echo $username;?>" />
                 <label for="password" class="formLabel">Password</label>
                 <input type="password" name="password" id="passwordLogin" value="<?php echo $password;?>" maxlength="8" />
                 <span class="error"><?php echo $loginErr;?></span>
                 <input type="submit" id="loginSubmit" name="loginSubmit" value="Log in" class="btn" />
               </fieldset>
      </form>
             <!--   <h2>No network? No problem</h2>
   <p>Take the offline test. Your results will be stored in local storage but as yet I am unable to get them out again. You can still get some feedback</p>
    <img src="img/wi_fi.gif" width="128" height="128" alt="offline">
    <form id="offline" method="post" action="postquizoffline.php">
     <input type="submit" id="loginSubmit" name="loginSubmit" value="Take offline test" class="btn right"/>
      </form>--> </div>
  </div>
         <!--  <p class='smiling'>Score:<?php echo $score ?></p>
  <p class='smiling'>Num:<?php echo $num ?></p>
  <p class='smiling'>Current Question:<?php echo $currentQuestion ?></p>
  <p>sessions</p>
  <p class='smiling'>firstName:<?php echo $_SESSION['firstName']?></p>
  <p class='smiling'>score:<?php echo $_SESSION['score'];?></p>
 
  <p class='smiling'>username:<?php echo $_SESSION['username'];?></p>
  <p class='smiling'>id:<?php echo $_SESSION['studentID'];?></p>
  <p class='smiling'>local:<?php echo $_SESSION['localStorageSelectedAnswers'];?></p>
 <p class='smiling'>attempt:<?php echo $_SESSION['attempt'];?></p>--> 
       </div>
</body>
</html>